package com.osfw.framework.web.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.antherd.smcrypto.sm2.Keypair;
import com.antherd.smcrypto.sm2.Sm2;
import com.osfw.framework.config.Global;
import com.osfw.framework.core.controller.BaseController;
import com.osfw.framework.exception.ServiceException;
import com.osfw.system.entity.manage.SysMenu;
import com.osfw.system.entity.manage.SysUser;
import com.osfw.system.service.manage.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


/**
 * 首页 DB Adminer
 */
@Controller
@RequestMapping("/osfw")
public class IndexController extends BaseController {
    private String prefix = "osfw";

    @Autowired
    private ISysMenuService sysMenuService;

    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap) {
        Keypair keypair = Sm2.generateKeyPairHex();
        mmap.put("publicKey", keypair.getPublicKey());
        StpUtil.getSession().set("privateKey", keypair.getPrivateKey());
        List<SysMenu> sysMenus = sysMenuService.selectMenusByUser(new SysMenu().setParentId(0l), getUserId());
        mmap.put("sysMenus", sysMenus);
        Object userName = StpUtil.getSession().get("userName");
        Object userAvatar = StpUtil.getSession().get("userAvatar");
        Object userPost = StpUtil.getSession().get("userPost");
        Object isAgreement = StpUtil.getSession().get("isAgreement");
        mmap.put("userName", userName);
        mmap.put("userAvatar", userAvatar);
        mmap.put("userPost", userPost);
        mmap.put("isAgreement", isAgreement);
        mmap.put("captchaEnabled", Global.isCaptchaEnabled());
        return  prefix + "/index";
    }

    // 系统首页
    @GetMapping("/main")
    public String main() {

        return  prefix + "/main";
    }

    // 用户协议
    @GetMapping("/agreement")
    public String agreement(ModelMap mmap) {
        SysUser sysUser = getSysUser();
        Object isAgreement = StpUtil.getSession().get("isAgreement");
        mmap.put("applicationName", Global.getConfig("osfw.name"));
        mmap.put("userId", sysUser.getUserId());
        mmap.put("userName", sysUser.getUserName());
        mmap.put("isAgreement", isAgreement);
        return  prefix + "/agreement";
    }

    @PostMapping("/agreeAgreement")
    @ResponseBody
    public boolean agreeAgreement(@Valid @RequestParam String usbKey, @Valid @RequestParam String userSign) {
        if(true) { // todo 校验签字是否本人是否篡改信息
            StpUtil.getSession().set("isAgreement", "1");
            return true;
        }else {
            ServiceException.throw500("非法签字，请确保您的签字及数字证书完整有效！");
        }
        return false;
    }

}
